import datetime
import math
import urllib3
import requests
import re
import json
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#k8s的api地址
url = "https://192.168.28.180:6443"

#k8s的token
token = "eyJhbGciOiJSUzI1NiIsImtpZCI6InVkQ0t5UllBd2NWdjBaRDVqaFdWbzBGOEV1YTMteXlkY1ZLVGstMFliNkkifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tdnFiejUiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiY2U1MjFjOWItMmEyNC00NmRlLWIxYWMtYzBjMDYxYzk2ZTYzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.GR-nDYm55pn-qQuU3OFdpGLwfUCrZ8EB8DBVy0U8fVUSkeISg4d1qnIn3g0PvzefllgrcRXziBlgG9yi1aE9RH0xGkOdReRM-oLrRCVzc5xBdQsflO80pFUpfIqAl5gnRG3XyN5UGxZRbUD8zKNdR5TSaikpnkDj04Kr6yw3oc7JUoUuP51qMmawdbK5Rmu1i_xKXf0TVsZF3idKpmhv0ZTCpMlDWZDH5emIr5ZNminx-Ly0cwcFxaP7oQBAyMLUoskF4mXPkvqu5k9tLDXx8hR595VLlapYhHR2aQ7ZQk6amFTbt5J9uUoyzW8RHI_IC_7_WsZHvGeybL613F5m-w"

def get_result(api_name):
    headers = {"Authorization":"Bearer "+token}
    print(url+api_name)
    json_data = requests.get(url+api_name,headers=headers,verify=False)
    return json_data.json()


#时间转换,把所有服务的创建时间变成运行时间
def Trantime(time_data):
    time = re.match(r"(\d+)-(\d+)-(\d+).*?(\d+):(\d+):(\d+)",time_data)
    total_send = round((datetime.datetime.now()-datetime.datetime(int(time.group(1)),int(time.group(2)),int(time.group(3)),int(time.group(4)),int(time.group(5)),int(time.group(6)))).total_seconds())
    return str(math.floor(total_send/86400)).split(".")[0]+"d"+str(math.floor((total_send%86400)/3600)).split(".")[0]+"h"

#把所有的单位转换成b
def Tranunit(unit_data):
    unit = re.match(r"(\d+)(.*)",unit_data)
    value = int(unit.group(1))
    if unit.group(2) == "K":
        return value*1000
    elif unit.group(2) == "Ki":
        return value*1024
    elif unit.group(2) == "M":
        return value*1000*1000
    elif unit.group(2) == "Mi":
        return value*1024*1024
    elif unit.group(2) == "G":
        return value*1000*1000*1000
    elif unit.group(2) == "Gi":
        return value*1024*1024*1024
    elif unit.group(2) == "n":
        return math.ceil(value/1000/1000)
    elif unit.group(2) == "m":
        return value
    else:
        return value

#获取所有k8s节点的信息
def get_node():
    print("获取所有k8s节点的信息")
    node_result = get_result("/api/v1/nodes")
    data = []
    for i in node_result.get("items"):
        data.append({"{#NAME}": i.get("metadata").get("name"),
                "{#STATUS}": [
                    i.get("status").get("conditions")[-1].get("type") if i.get("status").get("conditions")[-1].get(
                        "status") == "True" else "NotReady"],
                "{#IP}": [i.get("status").get("addresses")[0].get("address")],
                "{#KUBELET_VERSION}": [i.get("status").get("nodeInfo").get("kubeletVersion")],
                "{#OS_IMAGE}": [i.get("status").get("nodeInfo").get("osImage")],
                "{#CPU}": [str(i.get("status").get("capacity").get("cpu")) + "%"],
                "{#MEMORY}": [str(int(Tranunit(i.get("status").get("capacity").get("memory")) / 1000 / 1000 / 1000)) + "G"],
                "{#LIMIT_STORAGE}": [Tranunit(i.get("status").get("capacity").get("ephemeral-storage"))],
                "{#RUNTIME}": [Trantime(i.get("metadata").get("creationTimestamp"))],
                })
    print(data)


#获取k8s组件的健康信息
def get_health():
    print("获取k8s组件的健康信息")
    health_result = get_result("/api/v1/componentstatuses")
    for i in health_result.get("items"):
        data = {}
        data = {"{#NAME}": i.get("metadata").get("name"),
                "{#STATUS}": ["status",i.get("conditions")[0].get("type")],
                }
        print(data)


#获取k8s的所有namespaces 名称空间
def get_namespaces():
    print("获取k8s的所有名称空间")
    pod_result = get_result("/api/v1/namespaces")
    for i in pod_result.get("items"):
        data = {"#NAME":i.get("metadata").get("name"),
                "{#RUNTIME}":[Trantime(i.get("metadata").get("creationTimestamp"))]
                }
        print(data)


#获取k8s的所有pod
def get_pods():
    print("获取k8s的所有pod")
    pod_result = get_result("/api/v1/pods")
    for i in pod_result.get("items"):
        data = {"{#NAME}":i.get("metadata").get("name"),
                "{#NAMESPACE}": i.get("metadata").get("namespace"),
                "{#RUNTIME}":["runtime",Trantime(i.get("metadata").get("creationTimestamp"))],
                "{#STATUS}":["status",i.get("status").get("phase")],
                "{#RESTARTCOUNT}":["restartcount",i.get("status").get("containerStatuses")[0].get("restartCount")]
                }
        print(data)


#获取所有k8s节点的信息
get_node()
#获取k8s组件的健康信息
get_health()
#获取k8s的所有namespaces 名称空间
get_namespaces()
#获取k8s的所有pod
get_pods()
